<template>
  <div class="alloc-menu menu-create">
    <el-card>
      <div slot="header">
        <span>分配权限</span>
      </div>
      <el-tree :data="menus"
       :props="defaultProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkedKeys"
        ref="menu-tree">
      </el-tree>
      <div style="text-align: center; padding: 20px;">
        <el-button type="primary" @click="onSave">保存</el-button>
        <el-button @click="reset">清空</el-button>
      </div>
    </el-card>

  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import {
  getMenuNodeList,
  allocRoleMenus,
  getRoleMenus
} from '@/services/menu'
import { Tree } from 'node_modules/element-ui/types'

export default Vue.extend({
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      menus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedKeys: []
    }
  },
  created () {
    this.loadMenus()
    this.loadRoleMenus()
  },
  methods: {
    async loadRoleMenus () {
      const { data } = await getRoleMenus(this.roleId)
      this.getCheckedKeys(data.data)
    },
    getCheckedKeys (menus: any) {
      menus.forEach((menu: any) => {
        if (menu.selected) {
          this.checkedKeys = [...this.checkedKeys, menu.id] as never
        }
        if (menu.subMenuList) {
          this.getCheckedKeys(menu.subMenuList)
        }
      })
    },
    async loadMenus () {
      const {
        data
      } = await getMenuNodeList()
      this.menus = data.data
    },
    async onSave () {
      const menuIdList = (this.$refs['menu-tree'] as Tree).getCheckedKeys()
      await allocRoleMenus({
        roleId: this.roleId,
        menuIdList
      })
      this.$message.success('操作成功')
      this.$router.back()
    },
    reset () {
      (this.$refs['menu-tree'] as Tree).setCheckedKeys([])
    }
  }
})

</script>

<style lang="scss" scope></style>
